import $axios from 'axios';
import $Store from '@/store';
import $XEUtils from 'xe-utils'

const timeout = 5000; // 超时时间
const locat = $XEUtils.locat();
const VUE_APP_API_URL = process.env.VUE_APP_API_URL === '-1' ? locat.protocol + '//' + locat.hostname : process.env.VUE_APP_API_URL;
const VUE_APP_API_PORT = process.env.VUE_APP_API_PORT === '-1' ? ':' + locat.port + '/' : process.env.VUE_APP_API_PORT;
const URL_PORT = VUE_APP_API_URL + VUE_APP_API_PORT;

export default (option) => {
  // 默认配置
  const instance = $axios.create({
    method: 'GET',
    url: '',
    data: {},
    params: {},
    baseURL: URL_PORT + process.env.VUE_APP_API_URI,
    timeout: timeout,
    headers: {
      source: process.env.VUE_APP_API_SOURCE,
      Authorization: $XEUtils.isEmpty($Store.state.Authentication.access_token) ? process.env.VUE_APP_API_AUTHENTICATION : $Store.state.Authentication.access_token
    }
  })
  instance.interceptors.request.use(config => {
    return config;
  }, err => {
    return err
  })
  instance.interceptors.response.use(response => {
    if (200 === response.status) {
      const contentDisposition = response['headers']['content-disposition'];
      if (contentDisposition) {
        response.data['contentDisposition'] = contentDisposition;
      }
      if (203 === response.data.code || 403 === response.data.code) {
        console.error(response.data['msg'])
      } else if (200 !== response.data.code) {
        if (!contentDisposition) {
          console.error(response);
        }
      }
    } else {
      console.error(response);
    }
    return response.data
  }, err => {
    return err
  })
  return instance(option)
}